/**
 * 
 */
package org.zgstudio.ddlchecker;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Queue;

/**
 * A simple implementation of LinkCheckTaskPool.
 * 
 * @author zhguo
 * 
 */
public class SimpleLinkCheckTaskPool implements LinkCheckTaskPool {

    // TODO: check ConcurrentLinkedQueue which may improve performance
    private Queue<LinkCheckTask> taskColl = new LinkedList<LinkCheckTask>();

    /*
     * (non-Javadoc)
     * 
     * @see org.zgstudio.ddlchecker.LinkCheckTaskPool#getNextTask()
     */
    @Override
    public LinkCheckTask getNextTask() {
        synchronized (taskColl) {
            if (taskColl.isEmpty()) return null;
            else return taskColl.poll();
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.zgstudio.ddlchecker.LinkCheckTaskPool#getNextTask(int)
     */
    @Override
    public LinkCheckTask getNextTask(int who) {
        return getNextTask();
    }
    

    @Override
    public void addLinkCheckTask(LinkCheckTask task) {
        taskColl.add(task);
    }

    @Override
    public void build(Link[] links) throws TooManyURLsInTaskException {
        LinkCheckTask task;
        int nLinkUnit = 10, tmpNLinks = nLinkUnit, srcPos = 0;
        Link tmpLinks[] = new Link[nLinkUnit];
        for (int i = 0; ; i += tmpNLinks) {
            task = new LinkCheckTask();
            if (tmpNLinks > links.length - i) tmpNLinks = links.length - i;
            if (tmpNLinks <= 0) break;
            
            if (tmpNLinks != nLinkUnit) {
                Link tmpLinks2[] = new Link[tmpNLinks];
                System.arraycopy(links, i, tmpLinks2, 0, tmpNLinks);
                task.addURLs(tmpLinks2);
            } else {
                System.arraycopy(links, i, tmpLinks, 0, tmpNLinks);
                task.addURLs(tmpLinks);
            }
            taskColl.add(task);
        }
    }
}
